package org.nbict.iot.trash.mogo;

import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.nbict.iot.trident.mogo.codec.BigDecimalCodec;

import java.util.Arrays;
import java.util.List;

/**
 * Created by songseven on 18/6/20.
 */
@Deprecated
public class MongoDBClient {
    private MongoClient client;
    private MongoCollection<Document> collection;

    public MongoDBClient(String url, String username, String adminname,
                         String password, String database, String
                                 collectionName) {

        MongoClientOptions.Builder build = new MongoClientOptions.Builder();
        build.connectionsPerHost(50);   //与目标数据库能够建立的最大connection数量为50
        build.threadsAllowedToBlockForConnectionMultiplier(50);
        //如果当前所有的connection都在使用中，则每个connection上可以有50个线程排队等待
        build.maxWaitTime(1000 * 60 * 2);
        build.connectTimeout(1000 * 60 * 1);    //与数据库建立连接的timeout设置为1分钟
        build.socketTimeout(1000 * 60 * 1);
        CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),CodecRegistries.fromCodecs(new BigDecimalCodec())); //important
        MongoClientOptions myOptions = build.codecRegistry(codecRegistry).build();
        try {
            //数据库连接实例
            MongoCredential credential = MongoCredential.createCredential
                    (username, adminname, password.toCharArray());
            client = new MongoClient(new ServerAddress(url), Arrays.asList
                    (credential), myOptions);

        } catch (MongoException e) {
            e.printStackTrace(); //log
        }

        MongoDatabase db = this.client.getDatabase(database);
        this.collection = db.getCollection(collectionName);
    }

    public void insert(List<Document> documents, boolean ordered) {
        InsertManyOptions options = new InsertManyOptions();
        if (!ordered) {
            options.ordered(false);
        }

        this.collection.insertMany(documents, options);
    }

    public void update(Bson filter, Bson update, boolean upsert) {
        UpdateOptions options = new UpdateOptions();
        if (upsert) {
            options.upsert(true);
        }
        this.collection.updateMany(filter, update, options);
    }

    public void replace(Bson query, Document replaced) {
        this.collection.replaceOne(query, replaced);
    }

    public void close() {
        this.client.close();
    }
}
